package modes

import (
	"fmt"
)

type LiveCid struct {
	Id     int64   `json:"li_id" xorm:"id"`           //id
	CId    int64   `json:"li_cid" xorm:"cid"`         //班型id
	LiveId int64   `json:"li_live_id" xorm:"live_id"` //直播id
	CName  []Class `json:"c_name" xorm:"-"`           //班型名称
}

func (this *LiveCid) TableName() string {
	return "livecid"
}

func (this *LiveCid) Save() (int64, error) {
	return Db(1).Insert(this)
}

func (this *LiveCid) Get() (bool, error) {
	return Db(1).Get(this)
}

func (this *LiveCid) CidGet(cidlist []int64) (bool, error) {
	return Db(1).In("cid ", cidlist).Get(this)
}

func (this *LiveCid) delete(where string) (int64, error) {
	return Db(1).Where(where).Delete(this)
}
func (this *LiveCid) Del() (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.delete(where)
}
func (this *LiveCid) Count(where string) (int64, error) {
	var val LiveClass
	return Db(1).Where(where).Count(&val)
}
func (this *LiveCid) update(where string, field string) (int64, error) {
	return Db(1).Where(where).Cols(field).Update(this)
}

func (this *LiveCid) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where, field)
}

func (this *LiveCid) where(fage, count, page int, where, field string) ([]LiveCid, error) {
	list := make([]LiveCid, 0)
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(1).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(1).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}

func (this *LiveCid) Lookups(val *Pager) error {
	list := make([]LiveCid, 0)
	val.TName = "livecid"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.id", val.TName) // id
	default:
		field = fmt.Sprintf("%s.id", val.TName) // id
	}
	if 1 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	} else {
		sort = fmt.Sprintf("%s desc", field)
	}
	val.Total, _ = Db(1).Table(val.TName).Where(val.ToWhere()).Count(this)
	err := Db(1).Table(val.TName).
		Where(val.ToWhere()).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	if err == nil {
		val.List = list
		for i, row := range list {
			list[i].CName, _ = GetCname(row.CId)
		}
		val.List = list
	}
	return err

}
func GetCname(cid int64) ([]Class, error) {
	list := make([]Class, 0)
	w := fmt.Sprintf("id = %d", cid)
	err := Db(0).Where(w).Find(&list)
	return list, err
}
